#!/usr/bin/env bash
# Copyright © 2023 OpenIM. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Use:
# ./scripts/install/openim-msgtransfer.sh openim::msgtransfer::start

# Common utilities, variables and checks for all build scripts.




OPENIM_ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")"/../.. && pwd -P)
[[ -z ${COMMON_SOURCED} ]] && source "${OPENIM_ROOT}"/scripts/install/common.sh

SERVER_NAME="openim-msgtransfer"

function openim::msgtransfer::start() {

  rm -rf "$TMP_LOG_FILE"

  openim::log::info "Start OpenIM Msggateway, binary root: ${SERVER_NAME}"
  openim::log::status "Start OpenIM Msggateway, path: ${OPENIM_MSGTRANSFER_BINARY}"

  # Message Transfer Prometheus port list
  MSG_TRANSFER_PROM_PORTS=(openim::util::list-to-string ${MSG_TRANSFER_PROM_PORT} )

  openim::log::status "OpenIM Prometheus ports: ${MSG_TRANSFER_PROM_PORTS[*]}"
  
  openim::log::status "OpenIM Msggateway config path: ${OPENIM_MSGTRANSFER_CONFIG}"
  
  openim::log::info "openim maggateway num: ${OPENIM_MSGGATEWAY_NUM}"
  
  if [ "${OPENIM_MSGGATEWAY_NUM}" -lt 1 ]; then
    opeim::log::error "OPENIM_MSGGATEWAY_NUM must be greater than 0"
  fi
  
  if [ ${OPENIM_MSGGATEWAY_NUM} -ne $((${#MSG_TRANSFER_PROM_PORTS[@]} - 1)) ]; then
    openim::log::error "OPENIM_MSGGATEWAY_NUM must be equal to the number of MSG_TRANSFER_PROM_PORTS"
  fi
  
  for (( i=0; i<$OPENIM_MSGGATEWAY_NUM; i++ )) do
  openim::log::info "prometheus port: ${MSG_TRANSFER_PROM_PORTS[$i]}"
  PROMETHEUS_PORT_OPTION=""
  if [[ -n "${MSG_TRANSFER_PROM_PORTS[$i+1]}" ]]; then
      PROMETHEUS_MSG_TRANSFER_PORT="${MSG_TRANSFER_PROM_PORTS[$i+1]%,}"
      openim::util::stop_services_on_ports ${PROMETHEUS_MSG_TRANSFER_PORT}
      PROMETHEUS_PORT_OPTION="--prometheus_port ${PROMETHEUS_MSG_TRANSFER_PORT}"
  fi
  cmd="${OPENIM_MSGTRANSFER_BINARY} ${PROMETHEUS_PORT_OPTION} -c ${OPENIM_MSGTRANSFER_CONFIG} -n ${i}"
  nohup ${cmd} >> "${LOG_FILE}" 2> >(tee -a  "$TMP_LOG_FILE" | while read line; do echo -e "\e[31m${line}\e[0m"; done >&2) >/dev/null &
  #nohup ${OPENIM_MSGTRANSFER_BINARY} ${PROMETHEUS_PORT_OPTION} -c ${OPENIM_MSGTRANSFER_CONFIG} -n ${i} >> ${LOG_FILE} 2> >(tee -a "${STDERR_LOG_FILE}" "$TMP_LOG_FILE" >&2) &
  done
  return 0
}

function openim::msgtransfer::check() {
  PIDS=$(pgrep -f "${OPENIM_OUTPUT_HOSTBIN}/openim-msgtransfer")
  if [ -z "$PIDS" ]; then
      NUM_PROCESSES=0
  else
      NUM_PROCESSES=$(echo "$PIDS" | wc -l)
  fi
  if [ "$NUM_PROCESSES" -eq "$OPENIM_MSGGATEWAY_NUM" ]; then
    for PID in $PIDS; do
      if [[ "$OSTYPE" == "linux-gnu"* ]]; then
        ps -p $PID -o pid,cmd
        elif [[ "$OSTYPE" == "darwin"* ]]; then
        ps -p $PID -o pid,comm
      else
        openim::log::error "Unsupported OS type: $OSTYPE"
      fi
    done
  else
    openim::log::error "Expected $OPENIM_MSGGATEWAY_NUM openim msgtransfer processes, but found $NUM_PROCESSES msgtransfer processes."
    return 1
  fi
  return 0
}

function openim::msgtransfer::check_for_stop() {
  PIDS=$(pgrep -f "${OPENIM_OUTPUT_HOSTBIN}/openim-msgtransfer") || PIDS="0"
  if [  "$PIDS" = "0" ]; then
      return 0
  fi

  NUM_PROCESSES=$(echo "$PIDS" | wc -l | xargs)

  if [ "$NUM_PROCESSES" -gt 0 ]; then
    openim::log::error "Found $NUM_PROCESSES processes for $OPENIM_OUTPUT_HOSTBIN/openim-msgtransfer"
    for PID in $PIDS; do
      if [[ "$OSTYPE" == "linux-gnu"* ]]; then
        echo -e "\033[31m$(ps -p $PID -o pid,cmd)\033[0m"
      elif [[ "$OSTYPE" == "darwin"* ]]; then
        echo -e "\033[31m$(ps -p $PID -o pid,comm)\033[0m"
      else
        openim::log::error "Unsupported OS type: $OSTYPE"
      fi
    done
    openim::log::error "Processes have not been stopped properly."
  else
    openim::log::success "All openim-msgtransfer processes have been stopped properly."
  fi
  return 0
}


###################################### Linux Systemd ######################################
SYSTEM_FILE_PATH="/etc/systemd/system/${SERVER_NAME}.service"

# Print the necessary information after installation
function openim::msgtransfer::info() {
cat << EOF
openim-msgtransfer listen on: ${OPENIM_MSGTRANSFER_HOST}
EOF
}

# install openim-msgtransfer
function openim::msgtransfer::install() {
  pushd "${OPENIM_ROOT}"
  
  # 1. Build openim-msgtransfer
  make build BINS=${SERVER_NAME}
  
  openim::common::sudo "cp -r ${OPENIM_OUTPUT_HOSTBIN}/${SERVER_NAME} ${OPENIM_INSTALL_DIR}/${SERVER_NAME}"
  openim::log::status "${SERVER_NAME} binary: ${OPENIM_INSTALL_DIR}/${SERVER_NAME}/${SERVER_NAME}"
  
  openim::log::status "${SERVER_NAME} binary: ${OPENIM_INSTALL_DIR}/bin/${SERVER_NAME}"
  
  # 2. Generate and install the openim-msgtransfer configuration file (openim-msgtransfer.yaml)
  # nono
  
  # 3. Create and install the ${SERVER_NAME} systemd unit file
  echo ${LINUX_PASSWORD} | sudo -S bash -c \
  "SERVER_NAME=${SERVER_NAME} ./scripts/genconfig.sh ${ENV_FILE} deployments/templates/openim.service > ${SYSTEM_FILE_PATH}"
  openim::log::status "${SERVER_NAME} systemd file: ${SYSTEM_FILE_PATH}"
  
  # 4. Start the openim-msgtransfer service
  openim::common::sudo "systemctl daemon-reload"
  openim::common::sudo "systemctl restart ${SERVER_NAME}"
  openim::common::sudo "systemctl enable ${SERVER_NAME}"
  openim::msgtransfer::status || return 1
  openim::msgtransfer::info
  
  openim::log::info "install ${SERVER_NAME} successfully"
  popd
}


# Unload
function openim::msgtransfer::uninstall() {
  set +o errexit
  openim::common::sudo "systemctl stop ${SERVER_NAME}"
  openim::common::sudo "systemctl disable ${SERVER_NAME}"
  openim::common::sudo "rm -f ${OPENIM_INSTALL_DIR}/${SERVER_NAME}"
  openim::common::sudo "rm -f ${OPENIM_CONFIG_DIR}/${SERVER_NAME}.yaml"
  openim::common::sudo "rm -f /etc/systemd/system/${SERVER_NAME}.service"

  openim::log::info "uninstall ${SERVER_NAME} successfully"
}

# Status Check
function openim::msgtransfer::status() {
  # Check the running status of the ${SERVER_NAME}. If active (running) is displayed, the ${SERVER_NAME} is started successfully.
  if systemctl is-active --quiet "${SERVER_NAME}"; then
    openim::log::info "${SERVER_NAME} is running successfully."
  else
    openim::log::error "${SERVER_NAME} failed to start, maybe not installed properly"
    return 1
  fi
}

if [[ "$*" =~ openim::msgtransfer:: ]];then
  eval $*
fi
